home *** CD-ROM | disk | FTP | other *** search
/ Australian Personal Computer 2002 November / CD 1 / APC0211D1.ISO / workshop / prog / files / ActivePerl-5.6.1.633-MSWin32.msi / _c26d44f1765fe7a470ed052b68fd0df6 < prev    next >
Encoding:
Text File  |  2002-05-01  |  10.7 KB  |  387 lines

  1. package HTTP::Date;  # $Date: 2001/01/04 20:27:15 $
  2.  
  3. $VERSION = sprintf("%d.%02d", q$Revision: 1.43 $ =~ /(\d+)\.(\d+)/);
  4.  
  5. require 5.004;
  6. require Exporter;
  7. @ISA = qw(Exporter);
  8. @EXPORT = qw(time2str str2time);
  9. @EXPORT_OK = qw(parse_date time2iso time2isoz);
  10.  
  11. use strict;
  12. require Time::Local;
  13.  
  14. use vars qw(@DoW @MoY %MoY);
  15. @DoW = qw(Sun Mon Tue Wed Thu Fri Sat);
  16. @MoY = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
  17. @MoY{@MoY} = (1..12);
  18.  
  19. my %GMT_ZONE = (GMT => 1, UTC => 1, UT => 1, Z => 1);
  20.  
  21.  
  22. sub time2str (;$)
  23. {
  24.     my $time = shift;
  25.     $time = time unless defined $time;
  26.     my ($sec, $min, $hour, $mday, $mon, $year, $wday) = gmtime($time);
  27.     sprintf("%s, %02d %s %04d %02d:%02d:%02d GMT",
  28.         $DoW[$wday],
  29.         $mday, $MoY[$mon], $year+1900,
  30.         $hour, $min, $sec);
  31. }
  32.  
  33.  
  34. sub str2time ($;$)
  35. {
  36.     my $str = shift;
  37.     return undef unless defined $str;
  38.  
  39.     # fast exit for strictly conforming string
  40.     if ($str =~ /^[SMTWF][a-z][a-z], (\d\d) ([JFMAJSOND][a-z][a-z]) (\d\d\d\d) (\d\d):(\d\d):(\d\d) GMT$/) {
  41.     return eval {
  42.         my $t = Time::Local::timegm($6, $5, $4, $1, $MoY{$2}-1, $3-1900);
  43.         $t < 0 ? undef : $t;
  44.     };
  45.     }
  46.  
  47.     my @d = parse_date($str);
  48.     return undef unless @d;
  49.     $d[0] -= 1900;  # year
  50.     $d[1]--;        # month
  51.  
  52.     my $tz = pop(@d);
  53.     unless (defined $tz) {
  54.     unless (defined($tz = shift)) {
  55.         return eval { my $t = Time::Local::timelocal(reverse @d);
  56.               $t < 0 ? undef : $t;
  57.                 };
  58.     }
  59.     }
  60.  
  61.     my $offset = 0;
  62.     if ($GMT_ZONE{uc $tz}) {
  63.     # offset already zero
  64.     }
  65.     elsif ($tz =~ /^([-+])?(\d\d?):?(\d\d)?$/) {
  66.     $offset = 3600 * $2;
  67.     $offset += 60 * $3 if $3;
  68.     $offset *= -1 if $1 && $1 eq '-';
  69.     }
  70.     else {
  71.     eval { require Time::Zone } || return undef;
  72.     $offset = Time::Zone::tz_offset($tz);
  73.     return undef unless defined $offset;
  74.     }
  75.  
  76.     return eval { my $t = Time::Local::timegm(reverse @d);
  77.           $t < 0 ? undef : $t - $offset;
  78.         };
  79. }
  80.  
  81.  
  82. sub parse_date ($)
  83. {
  84.     local($_) = shift;
  85.     return unless defined;
  86.  
  87.     # More lax parsing below
  88.     s/^\s+//;  # kill leading space
  89.     s/^(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)[a-z]*,?\s*//i; # Useless weekday
  90.  
  91.     my($day, $mon, $yr, $hr, $min, $sec, $tz, $ampm);
  92.  
  93.     # Then we are able to check for most of the formats with this regexp
  94.     (($day,$mon,$yr,$hr,$min,$sec,$tz) =
  95.         /^
  96.      (\d\d?)               # day
  97.         (?:\s+|[-\/])
  98.      (\w+)                 # month
  99.         (?:\s+|[-\/])
  100.      (\d+)                 # year
  101.      (?:
  102.            (?:\s+|:)       # separator before clock
  103.         (\d\d?):(\d\d)     # hour:min
  104.         (?::(\d\d))?       # optional seconds
  105.      )?                    # optional clock
  106.         \s*
  107.      ([-+]?\d{2,4}|(?![APap][Mm]\b)[A-Za-z]+)? # timezone
  108.         \s*
  109.      (?:\(\w+\))?           # ASCII representation of timezone in parens.
  110.         \s*$
  111.     /x)
  112.  
  113.     ||
  114.  
  115.     # Try the ctime and asctime format
  116.     (($mon, $day, $hr, $min, $sec, $tz, $yr) =
  117.     /^
  118.      (\w{1,3})             # month
  119.         \s+
  120.      (\d\d?)               # day
  121.         \s+
  122.      (\d\d?):(\d\d)        # hour:min
  123.      (?::(\d\d))?          # optional seconds
  124.         \s+
  125.      (?:([A-Za-z]+)\s+)?   # optional timezone
  126.      (\d+)                 # year
  127.         \s*$               # allow trailing whitespace
  128.     /x)
  129.  
  130.     ||
  131.  
  132.     # Then the Unix 'ls -l' date format
  133.     (($mon, $day, $yr, $hr, $min, $sec) =
  134.     /^
  135.      (\w{3})               # month
  136.         \s+
  137.      (\d\d?)               # day
  138.         \s+
  139.      (?:
  140.         (\d\d\d\d) |       # year
  141.         (\d{1,2}):(\d{2})  # hour:min
  142.             (?::(\d\d))?       # optional seconds
  143.      )
  144.      \s*$
  145.        /x)
  146.  
  147.     ||
  148.  
  149.     # ISO 8601 format '1996-02-29 12:00:00 -0100' and variants
  150.     (($yr, $mon, $day, $hr, $min, $sec, $tz) =
  151.     /^
  152.       (\d{4})              # year
  153.          [-\/]?
  154.       (\d\d?)              # numerical month
  155.          [-\/]?
  156.       (\d\d?)              # day
  157.      (?:
  158.            (?:\s+|[-:Tt])  # separator before clock
  159.         (\d\d?):?(\d\d)    # hour:min
  160.         (?::?(\d\d(?:\.\d*)?))?  # optional seconds (and fractional)
  161.      )?                    # optional clock
  162.         \s*
  163.      ([-+]?\d\d?:?(:?\d\d)?
  164.       |Z|z)?               # timezone  (Z is "zero meridian", i.e. GMT)
  165.         \s*$
  166.     /x)
  167.  
  168.     ||
  169.  
  170.     # Windows 'dir' 11-12-96  03:52PM
  171.     (($mon, $day, $yr, $hr, $min, $ampm) =
  172.         /^
  173.           (\d{2})                # numerical month
  174.              -
  175.           (\d{2})                # day
  176.              -
  177.           (\d{2})                # year
  178.              \s+
  179.           (\d\d?):(\d\d)([APap][Mm])  # hour:min AM or PM
  180.              \s*$
  181.         /x)
  182.  
  183.     ||
  184.     return;  # unrecognized format
  185.  
  186.     # Translate month name to number
  187.     $mon = $MoY{$mon} ||
  188.            $MoY{"\u\L$mon"} ||
  189.        ($mon >= 1 && $mon <= 12 && int($mon)) ||
  190.            return;
  191.  
  192.     # If the year is missing, we assume first date before the current,
  193.     # because of the formats we support such dates are mostly present
  194.     # on "ls -l" listings.
  195.     unless (defined $yr) {
  196.     my $cur_mon;
  197.     ($cur_mon, $yr) = (localtime)[4, 5];
  198.     $yr += 1900;
  199.     $cur_mon++;
  200.     $yr-- if $mon > $cur_mon;
  201.     }
  202.     elsif (length($yr) < 3) {
  203.     # Find "obvious" year
  204.     my $cur_yr = (localtime)[5] + 1900;
  205.     my $m = $cur_yr % 100;
  206.     my $tmp = $yr;
  207.     $yr += $cur_yr - $m;
  208.     $m -= $tmp;
  209.     $yr += ($m > 0) ? 100 : -100
  210.         if abs($m) > 50;
  211.     }
  212.  
  213.     # Make sure clock elements are defined
  214.     $hr  = 0 unless defined($hr);
  215.     $min = 0 unless defined($min);
  216.     $sec = 0 unless defined($sec);
  217.  
  218.     # Compensate for AM/PM
  219.     if ($ampm) {
  220.     $ampm = uc $ampm;
  221.     $hr = 0 if $hr == 12 && $ampm eq 'AM';
  222.     $hr += 12 if $ampm eq 'PM' && $hr != 12;
  223.     }
  224.  
  225.     return($yr, $mon, $day, $hr, $min, $sec, $tz)
  226.     if wantarray;
  227.  
  228.     if (defined $tz) {
  229.     $tz = "Z" if $tz =~ /^(GMT|UTC?|[-+]?0+)$/;
  230.     } else {
  231.     $tz = "";
  232.     }
  233.     return sprintf("%04d-%02d-%02d %02d:%02d:%02d%s",
  234.            $yr, $mon, $day, $hr, $min, $sec, $tz);
  235. }
  236.  
  237.  
  238. sub time2iso (;$)
  239. {
  240.     my $time = shift;
  241.     $time = time unless defined $time;
  242.     my($sec,$min,$hour,$mday,$mon,$year) = localtime($time);
  243.     sprintf("%04d-%02d-%02d %02d:%02d:%02d",
  244.         $year+1900, $mon+1, $mday, $hour, $min, $sec);
  245. }
  246.  
  247.  
  248. sub time2isoz (;$)
  249. {
  250.     my $time = shift;
  251.     $time = time unless defined $time;
  252.     my($sec,$min,$hour,$mday,$mon,$year) = gmtime($time);
  253.     sprintf("%04d-%02d-%02d %02d:%02d:%02dZ",
  254.             $year+1900, $mon+1, $mday, $hour, $min, $sec);
  255. }
  256.  
  257. 1;
  258.  
  259.  
  260. __END__
  261.  
  262. =head1 NAME
  263.  
  264. HTTP::Date - date conversion routines
  265.  
  266. =head1 SYNOPSIS
  267.  
  268.  use HTTP::Date;
  269.  
  270.  $string = time2str($time);    # Format as GMT ASCII time
  271.  $time = str2time($string);    # convert ASCII date to machine time
  272.  
  273. =head1 DESCRIPTION
  274.  
  275. This module provides functions that deal the date formats used by the
  276. HTTP protocol (and then some more).  Only the first two functions,
  277. time2str() and str2time(), are exported by default.
  278.  
  279. =over 4
  280.  
  281. =item time2str( [$time] )
  282.  
  283. The time2str() function converts a machine time (seconds since epoch)
  284. to a string.  If the function is called without an argument, it will
  285. use the current time.
  286.  
  287. The string returned is in the format preferred for the HTTP protocol.
  288. This is a fixed length subset of the format defined by RFC 1123,
  289. represented in Universal Time (GMT).  An example of a time stamp
  290. in this format is:
  291.  
  292.    Sun, 06 Nov 1994 08:49:37 GMT
  293.  
  294. =item str2time( $str [, $zone] )
  295.  
  296. The str2time() function converts a string to machine time.  It returns
  297. C<undef> if the format of $str is unrecognized, or the time is outside
  298. the representable range.  The time formats recognized are the same as
  299. for parse_date().
  300.  
  301. The function also takes an optional second argument that specifies the
  302. default time zone to use when converting the date.  This parameter is
  303. ignored if the zone is found in the date string itself.  If this
  304. parameter is missing, and the date string format does not contain any
  305. zone specification, then the local time zone is assumed.
  306.  
  307. If the zone is not "C<GMT>" or numerical (like "C<-0800>" or
  308. "C<+0100>"), then the C<Time::Zone> module must be installed in order
  309. to get the date recognized.
  310.  
  311. =item parse_date( $str )
  312.  
  313. This function will try to parse a date string, and then return it as a
  314. list of numerical values followed by a (possible undefined) time zone
  315. specifier; ($year, $month, $day, $hour, $min, $sec, $tz).  The $year
  316. returned will B<not> have the number 1900 subtracted from it and the
  317. $month numbers start with 1.
  318.  
  319. In scalar context the numbers are interpolated in a string of the
  320. "YYYY-MM-DD hh:mm:ss TZ"-format and returned.
  321.  
  322. If the date is unrecognized, then the empty list is returned.
  323.  
  324. The function is able to parse the following formats:
  325.  
  326.  "Wed, 09 Feb 1994 22:23:32 GMT"       -- HTTP format
  327.  "Thu Feb  3 17:03:55 GMT 1994"        -- ctime(3) format
  328.  "Thu Feb  3 00:00:00 1994",           -- ANSI C asctime() format
  329.  "Tuesday, 08-Feb-94 14:15:29 GMT"     -- old rfc850 HTTP format
  330.  "Tuesday, 08-Feb-1994 14:15:29 GMT"   -- broken rfc850 HTTP format
  331.  
  332.  "03/Feb/1994:17:03:55 -0700"   -- common logfile format
  333.  "09 Feb 1994 22:23:32 GMT"     -- HTTP format (no weekday)
  334.  "08-Feb-94 14:15:29 GMT"       -- rfc850 format (no weekday)
  335.  "08-Feb-1994 14:15:29 GMT"     -- broken rfc850 format (no weekday)
  336.  
  337.  "1994-02-03 14:15:29 -0100"    -- ISO 8601 format
  338.  "1994-02-03 14:15:29"          -- zone is optional
  339.  "1994-02-03"                   -- only date
  340.  "1994-02-03T14:15:29"          -- Use T as separator
  341.  "19940203T141529Z"             -- ISO 8601 compact format
  342.  "19940203"                     -- only date
  343.  
  344.  "08-Feb-94"         -- old rfc850 HTTP format    (no weekday, no time)
  345.  "08-Feb-1994"       -- broken rfc850 HTTP format (no weekday, no time)
  346.  "09 Feb 1994"       -- proposed new HTTP format  (no weekday, no time)
  347.  "03/Feb/1994"       -- common logfile format     (no time, no offset)
  348.  
  349.  "Feb  3  1994"      -- Unix 'ls -l' format
  350.  "Feb  3 17:03"      -- Unix 'ls -l' format
  351.  
  352.  "11-15-96  03:52PM" -- Windows 'dir' format
  353.  
  354. The parser ignores leading and trailing whitespace.  It also allow the
  355. seconds to be missing and the month to be numerical in most formats.
  356.  
  357. If the year is missing, then we assume that the date is the first
  358. matching date I<before> current month.  If the year is given with only
  359. 2 digits, then parse_date() will select the century that makes the
  360. year closest to the current date.
  361.  
  362. =item time2iso( [$time] )
  363.  
  364. Same as time2str(), but returns a "YYYY-MM-DD hh:mm:ss"-formatted
  365. string representing time in the local time zone.
  366.  
  367. =item time2isoz( [$time] )
  368.  
  369. Same as time2str(), but returns a "YYYY-MM-DD hh:mm:ssZ"-formatted
  370. string representing Universal Time.
  371.  
  372.  
  373. =back
  374.  
  375. =head1 SEE ALSO
  376.  
  377. L<perlfunc/time>, L<Time::Zone>
  378.  
  379. =head1 COPYRIGHT
  380.  
  381. Copyright 1995-1999, Gisle Aas
  382.  
  383. This library is free software; you can redistribute it and/or
  384. modify it under the same terms as Perl itself.
  385.  
  386. =cut
  387.